<template>
<div style="height:100%;">
    <div class="containercontent">
        <div style="height:100%;">
            <!--{{getPlanData}}-->
            <!-- 条件搜索区域开始 -->
            <div class="penalrow selectw100">

                <div class="inlineblock verticalmiddle infoitem">
                    <div class="inlineblock verticalmiddle">
                        监测点
                    </div>
                    <!--<el-button style="float:right;padding:7px;" size="mini" class="" @click="itemsQuery.monitors=[]">清空</el-button>-->
                    <div class="inlineblock verticalmiddle informationItem" >
                        <el-select multiple collapse-tags clearable v-model="itemsQuery.monitors" placeholder="请选择" size="mini">
                            <el-option v-for="(item,index) in checkPoints" :key="index" :label="item.monitorName" :value="item.monitor">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <div class="inlineblock verticalmiddle infoitem">
                    <div class="inlineblock verticalmiddle">
                        检测项目
                    </div>
                    <!--<el-button style="float:right;padding:7px;" size="mini" class="" @click="itemsQuery.items=[]">清空</el-button>s-->
                    <div class="inlineblock verticalmiddle informationItem">
                        <el-select multiple clearable  filterable collapse-tags v-model="itemsQuery.items" placeholder="请选择" size="mini" @focus = "getItemsByTask(true)">
                            <el-option v-for="item in tableHeadArr" :key="item.item"  :label="item.itemName" :value="item.item">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <div class="inlineblock verticalmiddle infoitem">
                    <div class="inlineblock verticalmiddle" style="">
                        样品状态
                    </div>
                    <div class="inlineblock verticalmiddle informationItem">
                        <el-select v-model="itemsQuery.status" clearable placeholder="请选择" size="mini">
                            <el-option v-for="item in taskSampleStatus" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                 <el-button size="mini" type="primary" class="" @click="getResultByTask">搜索</el-button>

            </div>
            <!-- 条件搜索区域结束 -->
            <!-- 操作按钮开始 -->
            <!-- 操作按钮结束 -->
            <!-- 图例开始 -->
            <div class="penalrow selectw100">
                <div class="tuli">
                    图例
                </div>
                <!--540: 'jiancezhong',//'待接收',
          541: 'weijiaohe', //'待领取',
          542: 'waitExamine', //'待录入',
          543: 'chonglu', //'待重录',
          544: 'hasExamine', //'待校核',
          545: 'hasReview', //'待审核',
          546: 'chongcai', //'重采',
          547: 'finshed', //'已完成',-->
                <div class="tuli">
                    待接收
                    <div class="tuliColor jiancezhong"></div>
                </div>
                <div class="tuli">
                    待领取
                    <div class="tuliColor weijiaohe"></div>
                </div>
                <div class="tuli">
                    待录入
                    <div class="tuliColor waitExamine"></div>
                </div>
                <div class="tuli">
                    待重录
                    <div class="tuliColor chonglu"></div>
                </div>
                <div class="tuli">
                    待校核
                    <div class="tuliColor hasExamine"></div>
                </div>
                <div class="tuli">
                    待审核
                    <div class="tuliColor hasReview"></div>
                </div>
                <div class="tuli">
                    重采
                    <div class="tuliColor chongcai"></div>
                </div>
                <div class="tuli">
                    已完成：
                    <div class="tuliColor finshed"></div>
                </div>
                <div class="tuli">
                    废弃：
                    <div class="tuliColor feiqi"></div>
                </div>
                <div class="tuli" style = "position:absolute;top:12px;bottom:0;right:0;">
                    <el-button type="primary"  size="mini" style="float:right"  @click = "exportData">导出</el-button>
                </div>
            </div>
            <!-- 图例结束 -->
            <!-- 任务表格开始 -->
            <!--{{tableHeadArr}}-->
            <!--{{tableData}}-->
            <div class="penalrow resultexamineTable" style="display:block;height:calc(100% - 85px)">
                <!--@header-click="taskTableHeadClick"-->
                <el-table ref ="multipleTable" :data="tableData" style="width: 100%;"  height = "100%" size="mini" class = "tuliTableCon" cell-class-name="resultexamineTableCell"  :header-cell-class-name="headerCellClass"   v-if = "reload">
                    <el-table-column label="序号" width="49px" fixed>
                        <template slot-scope="scope">
                            {{scope.$index+1}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="样品名称" min-width="90px"  fixed show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="code" label="样品编号" min-width="90px" fixed  show-overflow-tooltip >
                    </el-table-column>
                    <!--<template v-for="col in tableHeadArr">-->
                        <!--:label="col.itemName"-->
                    <el-table-column v-for="(col,$index) in tableHeadArr1" :key="$index + '-label'"   align="center" :render-header="(h,obj) => labelHead(h,obj,col)">
                        <el-table-column :label="col.unitName == undefined ? '---' : col.unitName" width="160px">
                            <template slot-scope="scope">
                                <!--{{scope.row.itemMap[col.itemName]}}-->
                                <!--<div  :class="[classArr[scope.row.itemMap[col.itemName].status]]" @click="clickTableCell(scope.row.itemMap[col.itemName])" v-if="scope.row.itemMap&&scope.row.itemMap[col.itemName]">-->

                                    <!--{{scope.row.itemMap[col.itemName].value?scope.row.itemMap[col.itemName].value:taskStatusArr[scope.row.itemMap[col.itemName].status].label}}-->
                                    <!--如果状态是1,2,3,4,5  490的话 有值也要显示状态，否则有值的话就显示值，没值就显示状态-->
                                    <!--{{ changeStatus(scope.row.itemMap[col.itemName].status)? taskStatusArr[scope.row.itemMap[col.itemName].status].label:(scope.row.itemMap[col.itemName].value?scope.row.itemMap[col.itemName].value:taskStatusArr[scope.row.itemMap[col.itemName].status].label)}}-->
                                    <!--// 待重录,待校核,待审核,重采,已完成 有追溯-->
                                    <!--<div class="chakanzhuisu" v-if="scope.row.itemMap[col.itemName] != undefined && scope.row.itemMap[col.itemName].batch != undefined" @click.stop="retrospect(scope.row.itemMap[col.itemName])">追溯</div>
                                </div>-->
                                <!--<div  style="border:1px solid #777" v-if="scope.row.itemMap==undefined || scope.row.itemMap[col.itemName] == undefined">
                                    ×
                                </div>-->
                                 <div  :class="[classArr[scope.row.itemMap[col.item + col.detectability].status]]" @click="clickTableCell(scope.row.itemMap[col.item + col.detectability])" v-if="scope.row.itemMap&&scope.row.itemMap[col.item + col.detectability]">
                                     <!--如果状态是1,2,3,4,5  490的话 有值也要显示状态，否则有值的话就显示值，没值就显示状态-->
                                    {{ changeStatus(scope.row.itemMap[col.item + col.detectability].status)? taskStatusArr[scope.row.itemMap[col.item + col.detectability].status].label:(scope.row.itemMap[col.item + col.detectability].value?scope.row.itemMap[col.item + col.detectability].value:taskStatusArr[scope.row.itemMap[col.item + col.detectability].status].label)}}
                                    <!--// 待重录,待校核,待审核,重采,已完成 有追溯-->
                                    <div ref = "chakanzhuisu" class="chakanzhuisu" v-if="scope.row.itemMap[col.item + col.detectability] != undefined && scope.row.itemMap[col.item + col.detectability].batch != undefined" @click.stop="retrospect(scope.row.itemMap[col.item + col.detectability])">追溯</div>
                                </div>
                                <div  style="border:1px solid #777" v-if="scope.row.itemMap==undefined || scope.row.itemMap[col.item + col.detectability] == undefined">
                                    ×
                                </div>


                            </template>
                        </el-table-column>
                    </el-table-column>
                    <!--</template>-->
                </el-table>
            </div>
            <!-- 任务表格结束 -->
        </div>
        <!-- 任务编辑、详情开始 -->
        <div>
            <taskdetail v-if="taskDetailShow" :taskDetailShow="taskDetailShow"></taskdetail>
        </div>
        <!-- 任务编辑、详情结束 -->

    </div>
    <zhuisu :addVisible.sync="zhuisuShow" :testpanelData="testpanelData"></zhuisu>
    <div v-if="lookBatchListShow">
        <look-batch-list :jiancexiangmu="clickjiancexiangmu"></look-batch-list>
    </div>
    <complate-select :addVisible.sync="printTableShow" :printTemplateList="printTemplateList" :searchForm = "searchForm" :fromModel = "'detection'"></complate-select>

</div>
</template>

<script>
import {
    mapState
} from 'vuex'
import $ from 'jquery'

const taskdetail = () => import('../taskmanage/children/taskdetail.vue');
const zhuisu = () => import('./children/zhuisuCheck.vue');
const lookBatchList = () => import('./children/lookBatchList.vue');
const complateSelect = () =>
		import("./children/complateSelect.vue");

export default {
    props: ['getPlanData','title'],
    data() {
        let that = this;
        const generateData = _ => {
            const data = [];
            for (let i = 1; i <= 15; i++) {
                data.push({
                    key: i,
                    label: `备选项 ${i}`
                });
            }
            return data;
        };
        return {
            printTableShow:false,
            searchForm:{},
            msg: '',
            taskname: '',
            inspectionUnitTableDateValue: [],
            inspectionUnitTableDate: [{
                    inspectionUnitID: '002',
                    inspectionUnitName: '监测点二'
                },
                {
                    inspectionUnitID: '003',
                    inspectionUnitName: '监测点三一'
                },
                {
                    inspectionUnitID: '004',
                    inspectionUnitName: '监测点四'
                },
                {
                    inspectionUnitID: '005',
                    inspectionUnitName: '监测点一'
                },
                {
                    inspectionUnitID: '006',
                    inspectionUnitName: '监测点一'
                },
                {
                    inspectionUnitID: '007',
                    inspectionUnitName: '监测点一'
                }
            ],

            userName: '当前用户名',
            //任务状态
            taskState: [{
                    value: '001',
                    label: '未审核'
                },
                {
                    value: '002',
                    label: '已审核'
                }
            ],
            taskStateValue: '001',

            batchcreatetimestart: '',
            batchcreatetimeend: '',
            //截止日期可选范围
            pickerenddatefanwei: {
                disabledDate: function (time) {
                    let timeSpace = time.getTime() < new Date((that.batchcreatetimestart ? that.batchcreatetimestart : '1970-01-01')).getTime();
                    return timeSpace;
                }
            },
            datapickereditable: false,
            //任务列表
            taskListArrValue: '001',
            taskListArr: [],
            taskDetailShow: false,
            newTaskNamet: '',
            creatTaskStep: '0',
            creatTaskStatus: '',

            //监测点列表
            monitoringPoints: generateData(),
            //已选监测点 key数组
            monitoringPointsValue: [1, 4],
            currentPage: 1,
            abilityTableDateValue: '',
            zhuisuShow: false,
            sampleStatusValue: '',
            typeofAbilityTableDateValue: '',
            jiancexiangmuarrValue: [],
            jiancexiangmuarr: [],
            sampleStatus: [{
                    value: '000',
                    label: '待采样'
                },
                {
                    value: '003',
                    label: '待接样'
                },
                {
                    value: '004',
                    label: '待校核'
                },
                {
                    value: '005',
                    label: '待审核(如果为三级审核机构)'
                },
                {
                    value: '006',
                    label: '完成'
                }
            ],
            quanxuanFlag: false,
            lookBatchListShow: false,
            clickjiancexiangmu: '',

            itemsQuery: {
                task: '',
                monitors: [],
                items: [],
                status: null,
                // group: null
            },
            tableHeadArr: [],
            tableHeadArr1:[],
            tableData: [],
            checkPoints: [],
            classArr: {
                1: 'onlyBorder',//'无样',
                2: 'onlyBorder', //干扰
                3: 'onlyBorder',//'瓶坏',
                4: 'onlyBorder', //不测
                5: 'onlyBorder', //强制完成
                490:'onlyBorder', //草稿

                493: 'feiqi',//'废弃',
                540: 'jiancezhong', //'待接收',
                541: 'weijiaohe', //'待领取',
                542: 'waitExamine', //'待录入',
                543: 'chonglu', //'待重录',
                544: 'hasExamine', //'待校核',
                545: 'hasReview', //'待审核',
                546: 'chongcai', //'重采',
                547: 'finshed', //'已完成',


            },
            testpanelData: {},
            reload:true,
            printTemplateList:[],
        }
    },
    computed: {
        ...mapState(['entrustmentUnit', 'abilityTableDate', 'typeofAbilityTableDate', 'taskStatusArr', 'groupSelect','taskSampleStatus']),
        taskListTableHeight: function () {
            return (window.innerHeight - 400)
        }
    },
    created() {
        this.init();
        this.getItemsByTask();
        //	this.getResultByTask()
    },
    components: {
        taskdetail,
        zhuisu,
        lookBatchList,
        complateSelect
    },
    watch: {
        //当开始日期改变时，改变结束日期不可选日期部分
        batchcreatetimestart: function (val) {
            if (this.batchcreatetimeend) {
                if (this.batchcreatetimestart > this.batchcreatetimeend) {
                    this.batchcreatetimeend = this.batchcreatetimestart;
                } else {
                    this.batchcreatetimeend = new Date(this.batchcreatetimeend);
                }
            } else {
                if (this.batchcreatetimeend == null) {
                    this.batchcreatetimeend = '';
                } else {
                    this.batchcreatetimeend = null;
                }
            }
        },
        quanxuanFlag: function (val) {
            for (var i = 0; i < this.taskListArr.length; i++) {
                for (var prop in this.taskListArr[i]) {
                    // if( this.taskListArr[i][prop].hasOwnProperty('checked')&&this.taskListArr[i][prop].state =='waitExamine'){
                    if (this.taskListArr[i][prop].hasOwnProperty('checked')) {
                        this.taskListArr[i][prop].checked = val;
                    }
                }
            }
        }
    },
    methods: {
      exportData(){
        $('.chakanzhuisu').empty()
        let a = this.util.tableToExcel(this.$refs.multipleTable.$el ,'123')
        let formdata = new FormData()
        formdata.append('html', `<table>${a}</table> `)
        this.$axios({
          url: "/detection/toExcel.htm",
          method: 'post',
          responseType: 'blob',
          headers: {
          "Content-type": "multipart/form-data",
          'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined,
          },
          data: formdata
        }).then(res => {
          $('.chakanzhuisu').html('追溯')
          var name = this.getPlanData.name
          this.util.resultFileBlob(res,name)

        })
      },
        exportData1(){
            this.$http({
                method: 'post',
                apiUrl: '/printBusiness/getPrintTemList.htm',
                params: {
                    businessCode: "testSample"
                },
                isJson: false
            }).then(res => {
                if (res.code === 0) {

                    this.searchForm.items = this.itemsQuery.items != "" && this.itemsQuery.items.length != 0 ? this.itemsQuery.items : null;
                    this.searchForm.task = this.getPlanData.id;
                    this.searchForm.monitors = this.itemsQuery.monitors != "" && this.itemsQuery.monitors.length != 0 ? this.itemsQuery.monitors : null;
                    this.printTemplateList = res.data;
                    this.printTableShow = true;

                }
            })
        },
        changeStatus(status){
            if(status == 1 || status == 2 || status == 3 || status == 4 || status ==5 || status == 490){
                return true
            }else{
                return false
            }
        },
        // 计算表头的长度
        labelHead1(h, {
            column,
            index
        },col) {
            let l = column.label.length;
            let f = 12; //每个字大小，其实是每个字的比例值，大概会比字体大小差不多大一点，
            var minW = f * (l + 1);
            if (minW < 100) { // 如果计算出来的长度小于100 则长度为100
                column.minWidth = 100
            } else {
                column.minWidth = f * (l + 1) //字大小乘个数即长度 ,注意不要加px像素，这里minWidth只是一个比例值，不是真正的长度
                //然后将列标题放在一个div块中，注意块的宽度一定要100%，否则表格显示不完全
            }
            return h('div', {
                class: 'table-head',
                style: {
                    width: '100%'
                },
            }, [column.label])
        },
        labelHead(h, {
            column,
            index
        },col) {
            return [
                column.label,
                h(
                'el-tooltip',
                {
                    props: {
                        content: (function() {
                            return col.detectabilityName
                        })(),
                        placement: 'top'
                    }
                },
                [
                    h('div', {
                        class: {
                            'cell': true
                        }
                    },[col.itemName])
                ]
                )
            ]
        },
        reLoad(){
            this.reload = false;
            this.$nextTick(() => {
                this.reload = true;
            })
        },
        init() {
            this.itemsQuery.task = this.getPlanData.id
            this.$http({
                method: 'post',
                apiUrl: '/detection/getResultByTask.htm',
                params: this.itemsQuery,
                isJson: true,
            }).then(res => {
                if (res.code === 0) {

                    this.tableData = res.data
                    // 去掉重复的监测点
                    var chatList = res.data
                    var hash = {};
                    chatList = chatList.reduce(function (item, next) {
                            hash[next.monitor] ? "" : hash[next.monitor] = true && item.push(next);
                            return item
                        }, [])
                    this.checkPoints = chatList
                }
            })
        },
        //	追溯界面数据
        showresultentrypenal(row) {
            let id = row.batch;
            return new Promise((resolve, reject) => {
                this.$http({
                    method: 'post',
                    apiUrl: '/detection/getTestBatchAndItem.htm',
                    params: {
                        id: id
                    },
                    isJson: false
                }).then(res => {
                    if (res.code == 0) {
                        console.log(res)
                        resolve(res)

                    }
                })
            })

        },
        //	追溯点击事件
        retrospect(row) {
            this.showresultentrypenal(row).then(res => {
                console.log(res)
                this.testpanelData = res.data
                this.zhuisuShow = true
            })

        },
        //	获取列表数据
        getResultByTask() {
            this.getItemsByTask();
            this.itemsQuery.task = this.getPlanData.id
            this.$http({
                method: 'post',
                apiUrl: '/detection/getResultByTask.htm',
                params: this.itemsQuery,
                isJson: true,
            }).then(res => {
                if (res.code === 0) {
                    this.tableData = res.data
                }
            })
        },
        //	获取监测点列表
        getItemsByTask(isSelect) {
            this.itemsQuery.task = this.getPlanData.id
            var params = JSON.parse(JSON.stringify(this.itemsQuery))
            if(isSelect){
                params.items = [];
            }
            this.$http({
                method: 'post',
                apiUrl: '/detection/getItemsByTask.htm',
                params:params,
                isJson: true,
            }).then(res => {
                if (res.code === 0) {

                    if(isSelect){
                         var obj = {};
                        var data = res.data.reduce((cur,next) => {
                            obj[next.item] ? "" : obj[next.item] = true && cur.push(next);
                            return cur;
                        },[])
                        this.tableHeadArr = data
                    }else{
                        console.log(res.data)
                        this.tableHeadArr1 =res.data; //表头
                        this.reLoad();
                    }

                }
            })
        },
        //筛选任务类型，传入筛选值、行信息   如果value是多个值会循环筛选
        filterTag(value, row) {
            return row.taskType === value;
        },
        editTask(row) {
            // this.taskDetailShow=true;
            this.taskDetailShow = true;
        },
        //显示创建任务面板
        showCreatePenal() {
            this.creatTaskStep = '1';
        },
        //关不创建任务面板
        closeCreatePenal() {
            this.creatTaskStep = '0';
            this.creatTaskStatus = '';
        },
        //常规创建
        routineCreate() {
            this.creatTaskStep = '2';
            this.creatTaskStatus = 'routine';
        },
        //通过模板创建
        templateCreate() {
            this.creatTaskStep = '2';
            this.creatTaskStatus = 'template';
        },
        //
        gobackFirstStep() {
            this.creatTaskStep = '1';
            this.creatTaskStatus = '';
        },
        gotoThirdStep() {
            this.creatTaskStep = '3';
        },
        gobackSecondStep() {
            this.creatTaskStep = '2';
        },
        completeCreatePrelude(type) {
            this.closeCreatePenal();
            if (type == 'routine') {

            } else if (type == 'template') {

            }
            this.taskDetailShow = true;
        },
        newReport() {

        },
        handleSizeChange() {

        },
        handleCurrentChange() {

        },
        clickTableCell(opt) {
            // if(opt.state!='hasExamine'){
            //   opt.checked = !opt.checked;
            // }
            opt.checked = !opt.checked;
        },
        // taskTableHeadClick(column) {
        //     if (column.property && column.property != 'taskName') {
        //         this.clickjiancexiangmu = column.property;
        //         this.lookBatchListShow = true;
        //     }
        // },
        headerCellClass(col) {
            if (col.columnIndex > 1) {
                return 'jiancexiangmuClick'
            }
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.penalrow {
    padding: 5px 0;
}

.popupPanel {
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /*min-width: 60%;
    min-height: 60%;*/
    width: 650px;
    height: 531px;
    border-radius: 2px;
}

.popupPanelTitle {
    padding: 10px 20px;
    border-bottom: 1px solid #eee;
}

.createStep {
    /*position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:70%;*/
    position: relative;
    left: 50%;
    transform: translate(-50%, 0%);
    padding: 20px;
    height: calc(100% - 41px);
}

.createItems {
    padding: 5px 0px;
}

.createItems:last-child {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
    bottom: 10px;
}

.createItemsCont {
    display: inline-block;
    width: calc(100% - 100px);
    float: right;
}

.chakanzhuisu {
    position: absolute;
    left: 0;
    bottom: 0;
    color: #000;
    display: none;
    top: 0;
    width: 30px;
    border-right: 1px solid #383838;
    cursor: pointer;
}

/*// 待重录,待校核,待审核,重采,已完成 有追溯*/
.chonglu:hover>.chakanzhuisu,
.hasExamine:hover>.chakanzhuisu,
.hasReview:hover>.chakanzhuisu,
.chongcai:hover>.chakanzhuisu,
.finshed:hover>.chakanzhuisu {
    display: block;
}
</style><style>
.tuliTableCon .el-table__fixed-body-wrapper{
    top:61px !important;
}
/*.tuliTableCon .table-head {
    font-size: 12px !important;
}

.tuliTableCon.el-table .cell {
    position: relative;
}

.tuliTableCon.el-table .caret-wrapper {
    position: absolute;
    top: 2px;
    right: 0;
}

.tuliTableCon.el-table .cell,
.tuliTableCon.el-table th div {
    padding: 0 !important;
}

.tuliTableCon.el-table tr td .cell {
    padding: 5px 2px !important;
}

.tuliTableCon.el-table .cell,
.tuliTableCon.el-table th div,
.tuliTableCon.el-table--border td:first-child .cell,
.tuliTableCon.el-table--border th:first-child .cell {
    padding-left: 0 !important;
}

.tuliTableCon .el-table__header-wrapper {
    height: 36px;
}

.tuliTableCon.el-table th {
    padding: 0px !important;
}*/
.tuliTableCon.el-table th div{
    line-height:16px;
}
</style>
